import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Like, Repository } from 'typeorm';
import { CreateModelDto } from './dto/create-model.dto';
import { UpdateModelDto } from './dto/update-model.dto';
import { Model } from './entities/model.entity';
import { QueryModelDto } from './dto/query-model.dto';
import { CreateUserDto } from '../user/dto/create-user.dto';
import { User } from '../user/entities/user.entity';
import { UserInfoDto } from './dto/user-info.dto';
@Injectable()
export class ModelService {
    constructor(
        @InjectRepository(Model)
        private modelRepository: Repository<Model>,
        @InjectRepository(User)
        private userRepository: Repository<User>
    ) {
        
    }

  async create(createModelDto: CreateModelDto,user:UserInfoDto) {
    const exitUser = await this.userRepository.findOneBy({id: user?.id})

    if(!exitUser) {
        return {
            data: null
        }
    }

    const model = this.modelRepository.create({...createModelDto,user:exitUser});

    return await this.modelRepository.save(model);
  }

  async findAll(query: Omit<QueryModelDto,'description'|'content'>,user:UserInfoDto) {
    const {name,pageNum=1,pageSize=10} = query

    const [result, total] = await this.modelRepository
        .findAndCount({
            where:{
                deleted:false,
                name: name && Like(`%${name}%`),
                userId: user?.id
            },
            take: pageSize,
            skip: (pageNum - 1) * pageSize,
        }
    );

    return {
        rows: result,
        total
    }
  }

  async findOne(id: number) {
    return this.modelRepository.findOne({ where: { id } })
  }

  async update(id: number, updateModelDto: UpdateModelDto) {
    if(updateModelDto.default){
        await this.modelRepository
            .update({default:true}, {default:false})
    }

    await this.modelRepository.update(id, updateModelDto);

    return this.modelRepository.findOne({ where: { id } });
  }

  async remove(id: number) {
    return await this.modelRepository.delete(id)
  }
}
